﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OnlineVideos.View_Models;
using OnlineVideos.Data;
using Common.Library;
using System.ComponentModel;
using OnlineVideos.Common;
using Microsoft.Phone.Controls;
//using OnlineMovies.ViewModels;
using OnlineVideos.UI;
using MarkHeath.StarRating;
using OnlineVideos.Views;
using OnlineVideos.Entities;
using Microsoft.Phone.Shell;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace OnlineVideos
{
    public partial class ShowQuiz : UserControl
    {
        #region GlobalDeclaration
        public static ShowQuiz currentshowquiz = default(ShowQuiz);
        private bool IsDataLoaded;
        RatingPopup ratingPopup;
        ShowDetail detailModel;
        ObservableCollection<QuizList> objSubjectList;
        int SubjectId = 0;
        #endregion

        public ShowQuiz()
        {

            InitializeComponent();
            Loaded += ShowQuiz_Loaded;
            currentshowquiz = this;
            IsDataLoaded = false;
            ratingPopup = new RatingPopup();
            detailModel = new ShowDetail();
            objSubjectList = new ObservableCollection<QuizList>();
        }

        void ShowQuiz_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsDataLoaded == false)
            {
                GetPageDataInBackground();
                IsDataLoaded = true;
            }

        }

      

        public string time(string[] p)
        {
            string r = string.Empty;
            TimeSpan t = new TimeSpan(Convert.ToInt32(p[0]), Convert.ToInt32(p[1]), Convert.ToInt32(p[2]));

            r = ((t.Hours.ToString() == "0") ? "" : ((Convert.ToInt32(t.Hours) > 1) ? t.Hours.ToString() + " hours" : t.Hours.ToString() + " hour")) + ((t.Minutes.ToString() == "0") ? "" : ((Convert.ToInt32(t.Minutes) > 1) ? t.Minutes.ToString() + " minutes" : t.Minutes.ToString() + " minute")) + ((t.Seconds.ToString() == "0") ? "" : ((Convert.ToInt32(t.Seconds) > 1) ? t.Seconds.ToString() + " seconds" : t.Seconds.ToString() + " second"));


            return r;
        }

        public void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {

                                            a.Result = QuizManager.Getsubjects(AppSettings.ShowID/*, false*/);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {

                                            objSubjectList = (ObservableCollection<QuizList>)a.Result;
                                            if (objSubjectList.Count > 0)
                                            {
                                                lbxSubjectsList.Visibility = Visibility.Visible;
                                                if(((PivotItem)SubjectDetail.current.currentItem).Header.ToString()=="quiz")
                                                ((ApplicationBarMenuItem)SubjectDetail.current.ApplicationBar.MenuItems[1]).Text = "Add" + " " + "quiz";
                                                    else if(((PivotItem)SubjectDetail.current.currentItem).Header.ToString()=="practice tests")
                                                    ((ApplicationBarMenuItem)SubjectDetail.current.ApplicationBar.MenuItems[1]).Text = "Add" + " " + "practice tests";
                                                else
                                                    ((ApplicationBarMenuItem)SubjectDetail.current.ApplicationBar.MenuItems[1]).Text = "Add" + " " + "videos";
                                                txtxstackpl.Visibility = Visibility.Collapsed;
                                                lbxSubjectsList.ItemsSource = objSubjectList;
                                                tblksubjectstest.Visibility = Visibility.Collapsed;
                                                tblktext.Text = AppResources.ShowStartMessage as string;

                                            }
                                            else
                                            {
                                                tblksubjectstest.Text = "No " + AppResources.ShowQuizPivotTitle as string + " available";
                                                tblksubjectstest.Visibility = Visibility.Visible;
                                                //lbxSubjectsList.Visibility = Visibility.Collapsed;
                                            }

                                        }
                                      );

            bwHelper.RunBackgroundWorkers();


        }

        private void lbxSubjectsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          
            int showid = AppSettings.ShowUniqueID;
            if (lbxSubjectsList.SelectedIndex == -1)
                return;
            SubjectId = (lbxSubjectsList.SelectedItem as QuizList).QuizID;
            AppSettings.ShowQuizId = (SubjectId.ToString());
            if (Task.Run(async () => await Constants.connection.Table<QuizQuestions>().Where(i => i.ShowID == showid && i.QuizNo == SubjectId).FirstOrDefaultAsync()).Result != null)
            {
                txtxstackpl.Visibility = Visibility.Visible;
                tblkquestionsnotavailable.Visibility = Visibility.Collapsed;
            }
            else
            {
                txtxstackpl.Visibility = Visibility.Collapsed;
                tblkquestionsnotavailable.HorizontalAlignment = HorizontalAlignment.Center;
                tblkquestionsnotavailable.VerticalAlignment = VerticalAlignment.Center;
                tblkquestionsnotavailable.Text = "No Questions Available";
                tblkquestionsnotavailable.Visibility = Visibility.Visible;
            }
            lbxSubjectsList.Visibility = Visibility.Collapsed;
            ((ApplicationBarMenuItem)SubjectDetail.current.ApplicationBar.MenuItems[1]).Text = "Add" + " " + "questions";
            QuizManager.LoadMaxQuestionid();
            txttotquestions.Text = AppSettings.ShowMaxQuestionId.ToString();
            string timelimit = QuizManager.GetTimerForTest();
            string s = timelimit;
            string[] readlines2 = s.Split(':');
            txttimelimit.Text = time(readlines2);

            lbxSubjectsList.SelectedIndex = -1;
        }

        private void Quizpintostart_Click(object sender, RoutedEventArgs e)
        {
            string showLinkTitle;
            ListBoxItem selectedListBoxItem = this.lbxSubjectsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            if (selectedListBoxItem == null)
                return;
            showLinkTitle = (selectedListBoxItem.Content as QuizList).Name;
            AppSettings.ShowLinkTitle = AppSettings.ShowID + (selectedListBoxItem.Content as QuizList).Name;
            ShellTileHelper.PinSubjectLinkToStartScreen(AppSettings.ShowID, selectedListBoxItem.Content as QuizList);
        }

        private void Quizaddtofavorites_Click(object sender, RoutedEventArgs e)
        {
            detailModel.QuizAddToFavorites(lbxSubjectsList, sender as MenuItem, LinkType.Songs);
        }

        private void Quizsharelink_Click(object sender, RoutedEventArgs e)
        {
            detailModel.QuizPostAppLinkToSocialNetworks(lbxSubjectsList, sender as MenuItem, " Write the test ");
        }

        private void Quizratelink_Click(object sender, RoutedEventArgs e)
        {

            detailModel.QuizRateThisLink(lbxSubjectsList, sender as MenuItem, "SubjectDetail");
        }

        private void imgstart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            QuizManager.deletestoriongdata();
            (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(NavigationHelper.getQuestionDisplay());
        }

        private void ContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            //  ContextMenuHelper.ContextMenu_Opened(sender);
            ContextMenu mainmenu = sender as ContextMenu;
            foreach (MenuItem contextMenuItem in mainmenu.Items)
            {
                ListBoxItem selectedListBoxItem = this.lbxSubjectsList.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                if (contextMenuItem.Name == "Pin")
                {
                    if (ShellTileHelper.IsPinned(AppSettings.ShowID + (selectedListBoxItem.Content as QuizList).Name))
                    {
                        contextMenuItem.Header = Constants.UnpinFromStartScreen;
                    }
                    else
                    {
                        contextMenuItem.Header = Constants.PinToStartScreen;
                    }
                }
                if (contextMenuItem.Name == "Rating")
                {
                    if(ResourceHelper.AppName==Apps.DrivingTest.ToString())
                        contextMenuItem.Header = "rate this test";
                    else
                    contextMenuItem.Header ="rate this quiz";
                }
                if (contextMenuItem.Name.Contains("favorites"))
                {
                    int showid1 = Convert.ToInt32(AppSettings.ShowID);
                    int linkid = (selectedListBoxItem.Content as QuizList).LinkID;
                 
                    if (Task.Run(async () => await Constants.connection.Table<QuizList>().Where(i => i.ShowID == showid1 && i.LinkID == linkid).FirstOrDefaultAsync()).Result.IsFavourite == false)
                    {
                        contextMenuItem.Header = "add to favorites";
                    }
                    else
                        contextMenuItem.Header = "remove from favorites";
                }


            }
            int showid = AppSettings.ShowUniqueID;
            if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
            {

                var item = mainmenu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                item.IsEnabled = true;
            }
            else
            {
                var item = mainmenu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                item.IsEnabled = false;
            }
        }

        private void imgcancel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            txtxstackpl.Visibility = Visibility.Collapsed;
            lbxSubjectsList.Visibility = Visibility.Visible;
            if(ResourceHelper.ProjectName==Apps.Online_Education.ToString())
            ((ApplicationBarMenuItem)SubjectDetail.current.ApplicationBar.MenuItems[1]).Text = "Add" + " " + "quiz";
            else
                ((ApplicationBarMenuItem)SubjectDetail.current.ApplicationBar.MenuItems[1]).Text = "Add" + " " + "practice tests";
        }

        private void del_Click_1(object sender, RoutedEventArgs e)
        {
            MenuItem menu = sender as MenuItem;
            ListBoxItem selectedListBoxItem = lbxSubjectsList.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
        
            int showid = Convert.ToInt32((selectedListBoxItem.Content as QuizList).ShowID);
            int quizno = (selectedListBoxItem.Content as QuizList).QuizID;

            ShowLinks xquery = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(id => id.ShowID == showid && id.LinkOrder == quizno && id.LinkType == "Quiz").FirstOrDefaultAsync()).Result;
            if (xquery!=null)
            {
                if (Task.Run(async()=>await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                {
                    Task.Run(async () => await Constants.connection.DeleteAsync(xquery));
                    
                }
            }
            QuizList xquery1 =Task.Run(async () => await Constants.connection.Table<QuizList>().Where(id => id.ShowID == showid && id.QuizID == quizno).FirstOrDefaultAsync()).Result;
            if (xquery1!=null)
            {
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                {
                    Task.Run(async () => await Constants.connection.DeleteAsync(xquery1));
                }
            }
            List<QuizQuestions> xquery2 = Task.Run(async () => await Constants.connection.Table<QuizQuestions>().Where(id => id.ShowID == showid && id.QuizNo == quizno).ToListAsync()).Result;
            if (xquery2.Count() > 0)
            {
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                {
                    foreach (var ss in xquery2)
                    {
                        if (Task.Run(async()=>await Storage.FileExists("Images/QuestionsImage/" + showid + "/" + ss.Image + ".jpg")).Result)
                        {
                            Storage.DeleteFile("Images/QuestionsImage/" + showid + "/" + ss.Image + ".jpg");
                        }
                        Task.Run(async () => await Constants.connection.DeleteAsync(ss));
                    }
                 
                }
            }
            GetPageDataInBackground();
        }



    }
}
